package com.twang.stock.ebay;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class EbayFileReader {
        public static List<Map<String, String>> parseItems(String filePath) {
            List<Map<String, String>> results = new ArrayList<>();

            try {
                Document doc = Jsoup.parse(new File(filePath), "UTF-8");
                Elements itemWrappers = doc.select("div.s-item__wrapper.clearfix");

                for (Element wrapper : itemWrappers) {
                    Map<String, String> itemInfo = new HashMap<>();

                    // 修改点：使用 select().first() 替代 selectFirst()
                    Elements locationSpans = wrapper.select("span.s-item__location.s-item__itemLocation");
                    if (!locationSpans.isEmpty()) {
                        itemInfo.put("location", locationSpans.first().text());
                    }

                    // 同样修改卖家信息提取
                    Elements sellerInfoSpans = wrapper.select("span.s-item__seller-info-text");
                    if (!sellerInfoSpans.isEmpty()) {
                        itemInfo.put("seller_info", sellerInfoSpans.first().text());
                    }

                    if (!itemInfo.isEmpty()) {
                        results.add(itemInfo);
                    }
                }

            } catch (IOException e) {
                System.err.println("文件读取错误: " + e.getMessage());
            }

            return results;
        }

//        public static void main(String[] args) {
//            String filePath = "C:\\Users\\wangt\\Desktop\\Ebay\\解析文件\\Lining from China for sale _ eBay.txt";
//            // 使用示例
//            List<Map<String, String>> items = parseItems(filePath);
//
//            for (Map<String, String> item : items) {
//                System.out.println("Location: " + item.getOrDefault("location", "N/A"));
//                System.out.println("Seller Info: " + item.getOrDefault("seller_info", "N/A"));
//                System.out.println("----------------------");
//            }
//        }



//    public synchronized static String getamazonPage(String urlString) {
//        HttpURLConnection connection = null;
//
//        try {
//            // 创建 URL 对象
//            URL url = new URL(urlString);
//
//            // 打开连接
//            connection = (HttpURLConnection) url.openConnection();
//
//            // 设置请求属性 (必须在连接之后设置)
//            connection.setRequestProperty("Accept-Charset", "UTF-8"); // 设置请求编码
//            // connection.setRequestProperty("Accept", "application/json"); // 可选的请求头
//
//            // 设置请求方法
//            connection.setRequestMethod("GET");
//
//            // 获取响应码
//            int responseCode = connection.getResponseCode();
//            System.out.println("Response Code: " + responseCode);
//
//            String contentType = connection.getContentType();
//            System.out.println("查看服务器返回的编码信息 Content-Type: " + contentType); // 查看服务器返回的编码信息
//
//            // 读取响应内容
//            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
//            String inputLine;
//            StringBuilder response = new StringBuilder();
//
//            while ((inputLine = in.readLine()) != null) {
//                response.append(inputLine);
//            }
//            in.close();
//
//            // 打印响应内容
//            //System.out.println("Response Content: " + response.toString());
//            return response.toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (connection != null) {
//                connection.disconnect();
//            }
//        }
//        return "";
//
//    }


    public static void main(String[] args) {
        GetRequest();
    }


    private static void GetRequest() {
        // 目标URL（包含搜索参数）
        String url = "https://www.amazon.com/s?k=shoes&crid=F1AGJU5GF10&sprefix=shoes%2Caps%2C408&ref=nb_sb_noss_1";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建GET请求
            HttpGet httpGet = new HttpGet(url);

            // 设置请求头（模拟浏览器访问）
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36");
            httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            httpGet.setHeader("Accept-Encoding", "gzip, deflate, br, zstd");
            httpGet.setHeader("Referer", "https://www.amazon.com/-/zh/ref=nav_logo");
            httpGet.setHeader("Cookie", "session-id=130-8138511-6012064; ..."); // 完整cookie见原始请求头

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 处理响应
                if (response.getStatusLine().getStatusCode() == 200) {
                    String htmlContent = EntityUtils.toString(response.getEntity());
                    System.out.println("获取到的HTML内容长度：" + htmlContent.length());
                    // 这里可以添加HTML解析逻辑（如使用Jsoup解析商品信息）
                } else {
                    System.out.println("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
